import NavBar from '@/components/NavBar'
import { RootState } from '@/store'
import { getUserProfile, setUserInfo, setUserPhoto } from '@/store/action/user'
import history from '@/utils/history'
import { DatePicker, List, Modal, Popup, Toast } from 'antd-mobile'
import { useEffect, useRef, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import styles from './index.module.scss'
import classNames from 'classnames'
import { Profile } from '@/store/reducer/user'
import Input from '@/components/Input'
import Textarea from '@/components/Textarea'
import dayjs from 'dayjs'
import { removeTokenInfo } from '@/utils/storage'

export default function ProfileEdit() {
  
  // ------------从仓库中获取用户信息
  const { userProfile } = useSelector((state: RootState) => state.user)

  // ------------发送用户信息请求，把数据存到仓库
  const dispatch = useDispatch()
  useEffect(() => {
    if(userProfile.photo) return
    dispatch(getUserProfile())
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [dispatch])

  // ------------点击退出登录
  const exitLogin = async () => {
    const result = await Modal.confirm({
      content: '确定退出吗?',
    })
    if (result) {
      removeTokenInfo()
      dispatch({ type: 'user/token',payload:{} })
      history.push('/Login')
      Toast.show({ content: '退出成功', maskClassName: 'and_toast_win' })
    }
  }
  // ------------底部弹出层显示状态
  type popupBottomTypeType = '' | 'photo' | 'gender'
  type popupBottomType = {
    show: boolean;
    type: popupBottomTypeType;
  }
  const [popupBottom, setPopupBottom] = useState<popupBottomType>({ show: false, type: '' })
  // 隐藏3个弹窗
  const popupClose = () => {
    setPopupBottom({ show: false, type: '' })
    setPopupRight({ show: false, type: 'name' })
    setBirthdayShow(false)
  }
  const popupBottomSet: (type: popupBottomTypeType) => void = (type) => {
    setPopupBottom({ show: true, type })
  }

  // ------------上传修改头像相关逻辑
  const photoRef = useRef<HTMLInputElement>(null)
  const handeUpPhoto = async (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files) {
      // 拿到files信息
      const filesInfo = e.target.files[0]
      // 校验格式
      const type = ['image/jpeg', 'image/png']
      if (!type.includes(filesInfo.type)) {
        e.target.value = ''
        return Toast.show({ content: '文件格式错误', maskClassName: 'and_toast_err' })
      }
      // 校验大小
      if (filesInfo.size > 2 * 1024 * 1024) {
        e.target.value = ''
        return Toast.show({ content: '头像大小不能超过2M', maskClassName: 'and_toast_err' })
      }
      // 创建FormData对象
      const fd = new FormData()
      // 把files添加进FormData对象（‘photo’为后端需要的字段）
      fd.append('photo', filesInfo)
      // 调用封装的异步Action发送接口，存到仓库
      await dispatch(setUserPhoto(fd))
      // 隐藏遮罩
      popupClose()
      // 提示修改成功
      Toast.show({ content: '修改头像成功', maskClassName: 'and_toast_win' })
    }
  }

  // ------------修改用户其他资料（除头像）
  const setUserInfoFu = async (data: Partial<Profile>) => {
    await dispatch(setUserInfo(data))
    // 修改成功，改变仓库数据，隐藏遮罩
    popupClose()
    // 提示修改成功
    Toast.show({ content: '编辑成功', maskClassName: 'and_toast_win' })
  }


  // ------------右侧弹出层显示状态
  type popupRightTypeType = 'name' | 'intro'
  type popupRightType = {
    show: boolean;
    type: popupRightTypeType;
  }
  const [popupRight, setPopupRight] = useState<popupRightType>({ show: false, type: 'name' })

  const popupRightSet: (type: popupRightTypeType) => void = (type) => {
    // 打开的时候设置初始值
    setPopupRightValue({ value: userProfile[type], errMsg: '' })
    setPopupRight({ show: true, type })
  }

  // 打开的时候设置初始值
  // useEffect(() => {
  //   if (popupRight.show) setPopupRightErrMsg({ value: userProfile.name, errMsg: '' })
  // }, [popupRight, userProfile.name])

  // 右侧弹出层里面的输入框
  const [popupRightValue, setPopupRightValue] = useState({ value: '', errMsg: '' })
  const popupRightInput = (e: React.ChangeEvent<HTMLInputElement> | React.ChangeEvent<HTMLTextAreaElement>) => {
    if (e.target.value.trim() === '') setPopupRightValue({ value: e.target.value, errMsg: '不能为空' })
    else setPopupRightValue({ value: e.target.value, errMsg: '' })
  }
  // 点击提交
  const popupRightButFu = (type: popupRightTypeType) => {
    if (popupRightValue.value.trim() === '') return Toast.show({ content: '不能为空', maskClassName: 'and_toast_err' })
    setUserInfoFu({ [type]: popupRightValue.value })
  }
  // 输入框键盘事件
  const popupRightButInput = (e: React.KeyboardEvent<HTMLInputElement>, type: popupRightTypeType) => {
    if (e.key === 'Enter') popupRightButFu(type)
  }

  // ------------修改用户生日
  const [birthdayShow, setBirthdayShow] = useState(false)

  const birthdayFu = (value: Date) => {
    const birthday = dayjs(value).format('YYYY-MM-DD')
    setUserInfoFu({ birthday })
  }

  return (
    <div className={styles.root}>
      <div className='content'>
        {/* 顶部导航栏 */}
        <NavBar onBack={()=>history.push('/Layout/profile')}>个人资料</NavBar>

        <div className='wrapper'>
          {/* 列表一：显示头像、昵称、简介 */}
          <List className='profile-list'>
            <List.Item arrow extra={<img className='avatar' src={userProfile.photo} alt='' />} onClick={() => popupBottomSet('photo')} >
              头像
            </List.Item>

            <List.Item arrow extra={userProfile.name} onClick={() => popupRightSet('name')} >
              昵称
            </List.Item>

            <List.Item arrow extra={<span className='intro'>{userProfile.intro ? userProfile.intro.length > 10 ? userProfile.intro.substring(0, 10) + '...' : userProfile.intro : '暂无信息'}</span>} onClick={() => popupRightSet('intro')}>
              简介
            </List.Item>

            <List.Item arrow extra={userProfile.gender ? '男' : '女'} onClick={() => popupBottomSet('gender')}>
              性别
            </List.Item>
            <List.Item arrow extra={userProfile.birthday} onClick={() => setBirthdayShow(true)}>
              生日
            </List.Item>
          </List>

          {/* 文件选择框，用于头像图片的上传 */}
          <input accept='.png,.jpg' ref={photoRef} className='avatar-upload' type='file' onChange={(e) => handeUpPhoto(e)} />
        </div>

        {/* 底部栏：退出登录按钮 */}
        <div className='logout'>
          <button className='btn' onClick={exitLogin}>退出登录</button>
        </div>
      </div>

      {/* 点击头像和性别弹出的底部弹出层 */}
      <Popup visible={popupBottom.show} position='bottom' bodyClassName='popup-bottom-list' onMaskClick={() => popupClose()}>
        {popupBottom.type === 'photo' ?
          <>
            <div className='list-item' onClick={() => photoRef.current?.click()}>拍照</div>
            <div className='list-item' onClick={() => photoRef.current?.click()}>本地选择</div>
          </>
          :
          <>
            <div className={classNames('list-item', userProfile.gender ? 'self_noneAc' : '')} onClick={() => setUserInfoFu({ gender: 1 })}>男</div>
            <div className={classNames('list-item', userProfile.gender ? '' : 'self_noneAc')} onClick={() => setUserInfoFu({ gender: 0 })}>女</div>
          </>
        }
        <div className='list-item' onClick={() => popupClose()}>取消</div>
      </Popup>

      {/* 点击昵称和简介 -右侧弹出层 */}
      <Popup visible={popupRight.show} position='right' bodyClassName='popup-right' destroyOnClose>
        <NavBar right=
          {<span className="submit-btn" onClick={() => popupRightButFu(popupRight.type)}>提交</span>}
          onBack={popupClose}>编辑用户信息</NavBar>
        <div className='edit-content'>
          {popupRight.type === 'name' ?
            <>
              <h3 className='edit-title'>编辑昵称</h3>
              <Input className='edit-input' onKeyUp={(e) => popupRightButInput(e, popupRight.type)} value={popupRightValue.value} maxLength={10} onChange={(e) => popupRightInput(e)} errMsg={popupRightValue.errMsg} autoFocus />
            </>
            :
            <>
              <h3 className='edit-title'>编辑简介</h3>
              <Textarea value={popupRightValue.value} maxLength={100} onChange={(e) => popupRightInput(e)} errMsg={popupRightValue.errMsg} autoFocus />
            </>
          }
        </div>
      </Popup>

      {/* 点击生日-日期弹出层 */}
      <DatePicker visible={birthdayShow} min={new Date('1960-01-01')} max={new Date()} value={new Date(userProfile.birthday)} onClose={() => setBirthdayShow(false)} onConfirm={(value: Date) => birthdayFu(value)} />

    </div>
  )
}
